這幾日我們已經知道如何在Azure上建立Redis Cache,並學會如何操作,現在只需修改Workflow.ts程式,請求口罩公開資料集前,先判斷Redis Cache中是否已有資料,如果Cache中資料的存入時間相差不到30秒則由Azure Cache for Redis取得資料,如果超過30秒則重新搜尋公開資料並存入Redis Cache中
Worflow.ts:
import * as lineService from "./lineService"
import * as RedisCache from "./RedisCache"
import axios from "axios"
export const findMaskStore = async (GPS: any, userId: string) => {
let maskSnapshot
let nearMaskStore = []
const timestamp = new Date().getTime()
maskSnapshot = await RedisCache.getMask('mask')
if (maskSnapshot == 'null' || (timestamp - maskSnapshot.updateTime) >= 30000) {
maskSnapshot = await getMaskFromOpenSource()
}
console.log(maskSnapshot)
for (let element of maskSnapshot.content.features) {
const storeGPS = element.geometry.coordinates
let R = 6371 // Radius of the earth in km
let dLon = (storeGPS[0] - GPS.lon) * (Math.PI / 180)
let dLat = (storeGPS[1] - GPS.lat) * (Math.PI / 180) // deg2rad below
let a =
Math.sin(dLat / 2) * Math.sin(dLat / 2) +
Math.cos((GPS.lat) * (Math.PI / 180)) * Math.cos((GPS.lat) * (Math.PI / 180)) *
Math.sin(dLon / 2) * Math.sin(dLon / 2)
let c = 2 * Math.atan2(Math.sqrt(a), Math.sqrt(1 - a))
let d = R * c // Distance in km
if (d < 0.4) {
nearMaskStore.push(element)
}
}
for (const store of nearMaskStore) {
const maskMessage = lineService.toMaskMessage(store)
lineService.pushMessage(maskMessage, userId)
}
}
const getMaskFromOpenSource = async () => {
const mastData = await axios.get('https://raw.githubusercontent.com/kiang/pharmacies/master/json/points.json')
const maskSnapshot = {
updateTime: new Date().getTime(),
content: mastData.data
}
await RedisCache.setMask('mask', maskSnapshot)
return maskSnapshot
}
由於昨天我們將Line官方帳號的cannelSecret, channelAccessToken與Redis Cache的REDISCACHEHOSTNAME,REDISCACHEKEY重要參數寫入新增config.ts檔案,因此需修改一下先前的lineService.ts程式
修改後lineService.ts如下:
import { LINE } from "../config"
import { Client, TextMessage } from "@line/bot-sdk"
export function replyMessage(text: string, replyToken: string) {
const textMessage = {
type: "text",
text: text
} as TextMessage
const client = new Client(LINE)
return client.replyMessage(replyToken, textMessage)
}
export function pushMessage(text: string, userId: string) {
const textMessage = {
type: "text",
text: text
} as TextMessage
const client = new Client(LINE)
return client.pushMessage(userId, textMessage)
}
export function toMaskMessage(nearMaskStore: any) {
const maskMessage =
`${nearMaskStore.properties.name}\n` +
`${nearMaskStore.properties.phone}\n` +
`${nearMaskStore.properties.address}\n` +
`成人口罩:${nearMaskStore.properties.mask_adult}\n` +
`兒童口罩:${nearMaskStore.properties.mask_child}`
return maskMessage
}
Workflow.ts 與 lineService.ts原本程式可參考-Day [10] Azure Functions-Line Chatbot實作(二)
最後祝大家中秋節快樂
連假還是要記得發文歐!